<template>
  <view class="goods-detail-page">
    <!-- 状态栏占位 -->
    <!-- #ifdef MP-WEIXIN -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    <!-- #endif -->
    
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-back" @click="goBack">
        <image class="back-icon" src="/static/Images/goods/Fanhui.png" mode="aspectFit"></image>
      </view>
      <view class="nav-search-container" @click="goSearch">
        <view class="nav-search-box">
          <image class="search-icon" src="/static/Images/goods/Sousu.png" mode="aspectFit"></image>
          <text class="search-placeholder">搜索喜欢的商品</text>
        </view>
      </view>
      <view class="nav-more" @click="showMore">
        <image class="more-icon" src="/static/Images/goods/Share.png" mode="aspectFit"></image>
      </view>
    </view>
    
    <!-- 商品主图和信息左右布局 -->
    <view class="goods-main-section">
      <!-- 左侧商品主图 -->
       <view class="goods-image-section">
         <image class="goods-image" :src="currentGoodsInfo.image || ''" mode="aspectFill"></image>
       </view>
      
      <!-- 右侧商品信息 -->
      <view class="goods-info-section">
        <view class="goods-title-section">
          <text class="goods-title">{{ currentGoodsInfo.title || '商品名称' }}</text>
        </view>
        <view class="price-section" :key="priceStockUpdateKey">
          <view class="price-container">
            <text class="price-symbol">¥</text>
            <text class="price-number">{{ getCurrentPrice() }}</text>
          </view>
          <text class="stock-info">当前库存：{{ getCurrentStock() }}</text>
        </view>
      </view>
    </view>
    
    <!-- 商品组件 - 条件渲染以兼容微信小程序 -->
    <!-- 直充商品组件 -->
    <DirectRechargeGoods 
      v-if="currentGoodsInfo.type === 1"
      ref="directRechargeGoods"
      :goodsInfo="currentGoodsInfo"
      :initialSelectedSpec="selectedSpec"
      @spec-change="handleSpecChange"
      @account-change="handleAccountChange"
      @account-type-change="handleAccountTypeChange"
      @quantity-change="handleQuantityChange"
      @order-params-change="handleOrderParamsChange"
      @price-stock-update="handlePriceStockUpdate"
    ></DirectRechargeGoods>
    
    <!-- 卡密商品组件 -->
    <CardKeyGoods 
      v-if="currentGoodsInfo.type === 2"
      ref="cardKeyGoods"
      :goodsInfo="currentGoodsInfo"
      :initialSelectedSpec="selectedSpec"
      @spec-change="handleSpecChange"
      @account-change="handleAccountChange"
      @account-type-change="handleAccountTypeChange"
      @quantity-change="handleQuantityChange"
      @order-params-change="handleOrderParamsChange"
      @price-stock-update="handlePriceStockUpdate"
    ></CardKeyGoods>
    
    <!-- 权益商品组件 -->
    <BenefitGoods 
      v-if="currentGoodsInfo.type === 3"
      ref="benefitGoods"
      :goodsInfo="currentGoodsInfo"
      :initialSelectedSpec="selectedSpec"
      @spec-change="handleSpecChange"
      @account-change="handleAccountChange"
      @account-type-change="handleAccountTypeChange"
      @quantity-change="handleQuantityChange"
      @order-params-change="handleOrderParamsChange"
      @price-stock-update="handlePriceStockUpdate"
    ></BenefitGoods>
    <!-- 保障服务 -->
    <view class="guarantee-service-section">
      <view class="guarantee-section">
        <view class="guarantee-item">
          <image class="guarantee-icon" src="/static/Images/goods/Zhengpin.png" mode="aspectFit"></image>
          <text class="guarantee-text">正品保障</text>
        </view>
        <view class="guarantee-item">
          <image class="guarantee-icon" src="/static/Images/goods/Anquan.png" mode="aspectFit"></image>
          <text class="guarantee-text">安全保障</text>
        </view>
        <view class="guarantee-item">
          <image class="guarantee-icon" src="/static/Images/goods/Jisu.png" mode="aspectFit"></image>
          <text class="guarantee-text">极速到账</text>
        </view>
        <view class="guarantee-item">
          <image class="guarantee-icon" src="/static/Images/goods/Shouhou.png" mode="aspectFit"></image>
          <text class="guarantee-text">售后服务</text>
        </view>
      </view>
    </view>
    
    <!-- 商品详情 -->
    <view class="product-detail-section">
      <text class="section-title">商品详情</text>
      <view class="detail-content" v-html="safeHtml(currentGoodsInfo.content || '')">
      </view>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="bottom-left">
        <view class="bottom-btn" @click="goHome">
          <image class="home-icon" src="/static/Images/goods/Shouye.png" mode="aspectFit"></image>
          <text class="bottom-btn-text">首页</text>
        </view>
        <view class="bottom-btn" @click="contactService">
          <image class="service-icon" src="/static/Images/goods/Kefu.png" mode="aspectFit"></image>
          <text class="bottom-btn-text">客服</text>
        </view>
        <view class="bottom-btn" @click="contactService">
          <image class="service-icon" src="/static/Images/goods/Dingdan.png" mode="aspectFit"></image>
          <text class="bottom-btn-text">订单</text>
        </view>
      </view>
      <view class="bottom-right">
        <view class="buy-btn" @click="buyNow">
          <text class="buy-btn-text">立即购买</text>
        </view>
      </view>
    </view>
    
    <!-- 立即购买弹窗 -->
    <Goodsbuy 
      :visible="showBuyModal" 
      :goodsInfo="currentGoodsInfo"
      :accountNumber="accountNumber"
      :orderId="currentOrderId"
      :quantity="quantity"
      :accountCount="getAccountCount()"
      :cardKeyOrderParams="cardKeyOrderParams"
      @close="closeBuyModal"
      @pay="handlePaymentComplete"
    />

    <!-- 登录引导弹窗 -->
    <LoginGuideModal
      :visible="showLoginGuide"
      :title="loginGuideTitle"
      :subtitle="loginGuideSubtitle"
      @close="closeLoginGuide"
      @login="goToLogin"
      @register="goToRegister"
    />
  </view>
</template>

<script>
import Goodsbuy from '@/components/Goodsbuy.vue'
import DirectRechargeGoods from '@/components/ChargeGoods.vue'
import CardKeyGoods from '@/components/CardKeyGoods.vue'
import BenefitGoods from '@/components/BenefitGoods.vue'
import LoginGuideModal from '@/components/LoginGuideModal.vue'
import { validatePhone, validateEmail } from '@/utils/validate.js'
import { goodsApi } from '@/utils/api'
import { userStorage } from '@/utils/storage'

export default {
  components: {
    Goodsbuy,
    DirectRechargeGoods,
    CardKeyGoods,
    BenefitGoods,
    LoginGuideModal
  },
  data() {
    return {
      // 状态栏高度
      statusBarHeight: 0,
      quantity: 1,
      selectedType: 'mobile',
      selectedDuration: '7days',
      accountType: 'single',
      accountNumber: '',
      accountList: [], // 多账号列表
      showBuyModal: false,
      showLoginGuide: false, // 登录引导模态框显示状态
      goodsId: null,
      loading: false,
      currentOrderId: '', // 保存当前创建的订单ID
      currentGoodsInfo: {
        title: '【账号充值】芒果TV会员7天',
        price: '18.92',
        stock: '999998',
        image: '',
        content: '',
        type: 1, // 商品类型：1-直冲商品，2-卡密商品
        specs: [], // 商品规格列表
        channel_ids: [], // 支持的渠道ID列表
        carmines: {} // 卡密商品的价格库存数据
      },
      selectedSpec: null, // 当前选中的规格
      selectedCarmine: null, // 当前选中的卡密
      accountTypes: [], // 账号类型列表
      selectedAccountType: null, // 当前选中的账号类型
      // 组件数据
      componentAccountData: null, // 从组件接收的账号数据
      cardKeyOrderParams: null, // 从CardKeyGoods组件接收的订单参数
      priceStockUpdateKey: 0, // 用于强制重新渲染价格和库存
      // 平台列表，包含编号、名称和ID
      platformList: [
         { id: 1, name: '咸鱼' },
         { id: 2, name: '得物' },
         { id: 3, name: '小红书' },
         { id: 4, name: '拼多多' },
         { id: 5, name: '淘宝' },
         { id: 6, name: '京东' },
         { id: 7, name: '抖音' },
         { id: 8, name: '限购' },
         { id: 9, name: 'API充值' }
       ],
       transactionRecords: [
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' }
      ]
    }
  },
  computed: {
    // 根据商品类型返回对应的组件名
    currentComponent() {
      switch (this.currentGoodsInfo.type) {
        case 1:
          return 'DirectRechargeGoods';
        case 2:
          return 'CardKeyGoods';
        case 3:
          return 'BenefitGoods';
        default:
          return null;
      }
    },

    // 登录引导标题（根据平台动态显示）
    loginGuideTitle() {
      // #ifdef MP-WEIXIN
      return '微信授权登录';
      // #endif
      
      // #ifndef MP-WEIXIN
      return '需要登录';
      // #endif
    },

    // 登录引导副标题（根据平台动态显示）
    loginGuideSubtitle() {
      // #ifdef MP-WEIXIN
      return '购买商品需要微信授权登录，享受更便捷的购物体验';
      // #endif
      
      // #ifndef MP-WEIXIN
      return '购买商品需要先登录，登录后可享受更多服务';
      // #endif
    }
  },
  onLoad(options) {
    // #ifdef MP-WEIXIN
    // 获取系统信息
    const systemInfo = uni.getSystemInfoSync()
    // 获取胶囊按钮信息
    const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
    // 计算状态栏高度：系统状态栏高度 + 胶囊按钮高度 + 额外间距
    this.statusBarHeight = (systemInfo.statusBarHeight || 0) + (menuButtonInfo.height || 32) + 8
    // #endif
    
    const id = options?.id || options?.goodsId || options?.goods_id || '';
    if (!id) {
      uni.showToast({ title: '未获取到商品ID', icon: 'none' });
      return;
    }
    this.goodsId = id;
    
    // 接收type参数，如果有的话
    const type = options?.type;
    if (type !== undefined && type !== null) {
      this.currentGoodsInfo.type = parseInt(type) || 1;
    }
    
    this.fetchGoodsInfo();
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateTo(
        {
          url:'/pages/goods/goodslist'
        }
      )
      
    },
    
    // 跳转搜索页面
    goSearch() {
      uni.navigateTo({
        url: '/pages/index/search'
      })
    },
    
    // 分享商品
    shareGoods() {
      uni.share({
        provider: 'weixin',
        scene: 'WXSceneSession',
        type: 0,
        href: 'https://example.com',
        title: '商品分享',
        summary: '快来看看这个商品',
        imageUrl: 'https://via.placeholder.com/200x200'
      })
    },
    
    // 更多操作
    showMore() {
      uni.showActionSheet({
        itemList: ['收藏商品', '举报商品'],
        success: (res) => {
          if (res.tapIndex === 0) {
            uni.showToast({
              title: '收藏成功',
              icon: 'success'
            })
          }
        }
      })
    },
    
    // 选择商品类型
    selectType(type) {
      this.selectedType = type
    },
    
    // 选择商品时长
    selectDuration(duration) {
      this.selectedDuration = duration
    },
    
    // 选择充值账号类型
    selectAccountType(accountType) {
      this.selectedAccountType = accountType;
    },
    
    // 选择账号输入类型（单个/多个）
    selectAccountInputType(type) {
      this.accountType = type;
      
      // 切换到单账号模式时，如果有多个账号，取第一个作为默认值
      if (type === 'single' && this.accountList.length > 0) {
        this.accountNumber = this.accountList[0];
        this.accountList = [];
      }
      
      // 切换到多账号模式时，如果有单个账号，添加到列表中
      if (type === 'multiple' && this.accountNumber.trim()) {
        if (!this.accountList.includes(this.accountNumber.trim())) {
          this.accountList.push(this.accountNumber.trim());
        }
        this.accountNumber = '';
      }
    },
    
    // 添加账号
    addAccount() {
      if (!this.accountNumber || !this.accountNumber.trim()) {
        uni.showToast({
          title: '请输入账号',
          icon: 'none'
        });
        return;
      }
      
      const account = this.accountNumber.trim();
      
      // 商品类型为1时，验证手机号格式
      if (this.currentGoodsInfo.type === 1 && !validatePhone(account)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        });
        return;
      }
      
      // 商品类型为3时，根据账号类型验证格式
      if (this.currentGoodsInfo.type === 3 && this.selectedAccountType) {
        if (this.selectedAccountType.name === '手机号' && !validatePhone(account)) {
          uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none'
          });
          return;
        }
        if (this.selectedAccountType.name === '邮箱' && !validateEmail(account)) {
          uni.showToast({
            title: '请输入正确的邮箱地址',
            icon: 'none'
          });
          return;
        }
      }
      
      // 检查是否已存在
      if (this.accountList.includes(account)) {
        uni.showToast({
          title: '账号已存在',
          icon: 'none'
        });
        return;
      }
      
      // 添加到列表
      this.accountList.push(account);
      this.accountNumber = ''; // 清空输入框
      
      uni.showToast({
        title: '账号添加成功',
        icon: 'success'
      });
    },
    
    // 移除账号
    removeAccount(index) {
      this.accountList.splice(index, 1);
      uni.showToast({
        title: '账号已移除',
        icon: 'success'
      });
    },
    
    // 减少数量
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--
      }
    },
    
    // 增加数量
    increaseQuantity() {
      const maxStock = this.getCurrentStock();
      if (this.quantity < maxStock) {
        this.quantity++;
      } else {
        uni.showToast({
          title: `您购买数量已超库存上限`,
          icon: 'none'
        });
      }
    },
    
    // 处理子组件的数量变化事件
    handleQuantityChange(newQuantity) {
      this.quantity = newQuantity;
    },
    
    // 处理卡密商品订单参数变化
    handleOrderParamsChange(orderParams) {
      this.cardKeyOrderParams = orderParams;
      console.log('接收到卡密商品订单参数:', orderParams);
    },
    
    // 回到首页
    goHome() {
      uni.reLaunch({
        url: '/pages/index/index'
      })
    },
    
    // 联系客服
    contactService() {
      uni.showToast({
        title: '客服功能待开发',
        icon: 'none'
      })
    },
    
    // 加入购物车
    addToCart() {
      uni.showToast({
        title: '已加入购物车',
        icon: 'success'
      })
    },
    
    // 立即购买
    async buyNow() {
      // 检查登录状态
      if (!userStorage.isLoggedIn()) {
        console.log('用户未登录，显示登录引导');
        this.showLoginGuide = true;
        return;
      }
      
      // 验证必填信息
      let accounts = '';
      
      console.log('立即购买 - 当前参数:');
      console.log('- 商品信息:', this.currentGoodsInfo);
      console.log('- 购买数量:', this.quantity);
      console.log('- 账号数量:', this.getAccountCount());
      console.log('- 组件账号数据:', this.componentAccountData);
      
      // 只有直冲商品(type=1)和权益商品(type=3)才需要验证账号信息
      if (this.currentGoodsInfo.type !== 2) {
        // 根据商品类型调用对应组件的验证方法
        let validationResult = null;
        
        if (this.currentGoodsInfo.type === 1) {
          // 直冲商品：调用DirectRechargeGoods组件的验证方法
          try {
            const directRechargeComponent = this.$refs?.directRechargeGoods;
            if (directRechargeComponent && typeof directRechargeComponent.validateAccountData === 'function') {
              validationResult = directRechargeComponent.validateAccountData();
            }
          } catch (error) {
            console.error('调用直冲商品验证方法失败:', error);
          }
        } else if (this.currentGoodsInfo.type === 3) {
          // 权益商品：调用BenefitGoods组件的验证方法
          try {
            const benefitGoodsComponent = this.$refs?.benefitGoods;
            if (benefitGoodsComponent && typeof benefitGoodsComponent.validateAccountData === 'function') {
              validationResult = benefitGoodsComponent.validateAccountData();
            }
          } catch (error) {
            console.error('调用权益商品验证方法失败:', error);
          }
        }
        
        // 如果有验证结果，检查是否通过验证
        if (validationResult) {
          if (!validationResult.valid) {
            uni.showToast({
              title: validationResult.message,
              icon: 'none'
            });
            return;
          }
          accounts = validationResult.accounts;
        } else {
          // 如果没有组件验证方法，使用原有的验证逻辑作为兜底
          if (this.accountType === 'single') {
            if (!this.accountNumber || !this.accountNumber.trim()) {
              uni.showToast({
                title: '充值账号不能为空',
                icon: 'none'
              });
              return;
            }
            accounts = this.accountNumber.trim();
          } else {
            // 多账号模式 - 收集所有账号（已添加的 + 输入框中的）
            let allAccounts = [...this.accountList];
            
            // 如果输入框中还有账号，也加入到列表中
            if (this.accountNumber && this.accountNumber.trim()) {
              const inputAccount = this.accountNumber.trim();
              if (!allAccounts.includes(inputAccount)) {
                allAccounts.push(inputAccount);
              }
            }
            
            if (allAccounts.length === 0) {
              uni.showToast({
                title: '请至少添加一个充值账号',
                icon: 'none'
              });
              return;
            }
            
            accounts = allAccounts;
          }
        }
      }

      if (this.quantity <= 0) {
        uni.showToast({
          title: '购买数量不能为0',
          icon: 'none'
        });
        return;
      }

      // 验证库存
      if (this.currentGoodsInfo.type === 2) {
        // 卡密商品验证 - 使用CardKeyGoods组件的验证方法
        try {
          const cardKeyComponent = this.$refs?.cardKeyGoods;
          if (cardKeyComponent && typeof cardKeyComponent.validateCarmineSelection === 'function') {
            const validationResult = cardKeyComponent.validateCarmineSelection(this.quantity);
            if (!validationResult.valid) {
              uni.showToast({
                title: validationResult.message,
                icon: 'none'
              });
              return;
            }
          } else {
            // 兜底验证逻辑
            if (!this.selectedCarmine) {
              uni.showToast({
                title: '请先选择卡密售价',
                icon: 'none'
              });
              return;
            }
            if (this.quantity > parseInt(this.selectedCarmine.allcount)) {
              uni.showToast({
                title: '下单失败，卡密库存不足',
                icon: 'none'
              });
              return;
            }
          }
        } catch (error) {
          console.error('卡密商品验证失败:', error);
        }
      } else {
        // 其他商品验证
        const currentStock = this.getCurrentStock();
        if (currentStock === '无' || currentStock === 0) {
          uni.showToast({
            title: '下单失败，库存不足',
            icon: 'none'
          });
          return;
        }
        
        if (this.quantity > currentStock) {
          uni.showToast({
            title: '下单失败，库存不足',
            icon: 'none'
          });
          return;
        }
      }

      try {
        uni.showLoading({ title: '正在创建订单...' });
        
        // 构造 goodsList 参数
        const goodsListItem = {
          id: this.goodsId,
          count: this.quantity,
          specs_id: this.selectedSpec ? this.selectedSpec.id : '', // 所选规格id
          remark: '', // 备注
          temp_id: this.selectedAccountType ? this.selectedAccountType.id : null,
        };
        
        // 根据商品类型处理不同的参数
        const orderType = this.currentGoodsInfo.type || 1; // 使用商品的实际类型
        if (orderType === 1 || orderType === 3) {
          // 直冲订单和账号类型商品都需要上传充值账户，多个用数组上传
          if (this.accountType === 'multiple') {
            goodsListItem.accounts = this.accountList; // 多账号模式，直接使用数组
          } else {
            goodsListItem.accounts = [accounts]; // 单账号模式，包装成数组
          }
        } else if (orderType === 2) {
          // 卡密订单需要上传carmines参数 - 使用智能分配结果
          try {
            const cardKeyGoods = this.$refs?.cardKeyGoods;
            if (cardKeyGoods && typeof cardKeyGoods.getOrderParams === 'function') {
              const orderParams = cardKeyGoods.getOrderParams();
              goodsListItem.carmines = orderParams.carmines;
              // 保存详细的分配信息，用于传递给支付组件
              this.cardKeyOrderParams = orderParams;
            } else if (this.cardKeyOrderParams && this.cardKeyOrderParams.carmines) {
              goodsListItem.carmines = this.cardKeyOrderParams.carmines;
            } else {
              goodsListItem.carmines = this.buildCarminesParams();
            }
          } catch (error) {
            console.error('获取卡密订单参数失败:', error);
            goodsListItem.carmines = this.buildCarminesParams();
          }
        }
        
        const goodsList = [goodsListItem];

        // 构造完整的请求参数
        const orderParams = {
          goodsList,
          remark: '',
          type: orderType, // 1:话费充值, 2:卡密订单，3:权益充值
          carmine_id: orderType === 2 && this.selectedCarmine ? this.selectedCarmine.id : null,
          accounts: (orderType === 1 || orderType === 3) ? (this.accountType === 'multiple' ? this.accountList : [accounts]) : []
        };

        // 调用创建订单接口
        let res;
        res = await goodsApi.createOrder(orderParams);
        uni.hideLoading();
        if (res?.data) {
          uni.showToast({
            title: '订单创建成功',
            icon: 'success'
          });
          
          // 保存订单ID并显示支付弹窗
          // 根据接口返回格式，data字段直接就是订单ID
          const orderId = res.data || res.data.id || res.data.order_id || res.data.orderId || res.id || '';
          console.log('提取的订单ID:', orderId);
          this.currentOrderId = String(orderId);
          
          if (!this.currentOrderId) {
            console.warn('警告：订单ID为空，响应数据:', res.data);
            uni.showToast({
              title: '订单ID获取失败',
              icon: 'none'
            });
            return;
          }
          
          this.showBuyModal = true;
        } else {
          uni.showToast({
            title: res?.msg || '订单创建失败',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error('创建订单失败:', error);
        uni.showToast({
          title: error?.message || '订单创建失败',
          icon: 'none'
        });
      }
    },
    
    // 关闭购买弹窗
    closeBuyModal() {
      this.showBuyModal = false;
    },
    
    // 处理支付完成事件
    handlePaymentComplete(paymentData) {
      console.log('支付完成:', paymentData);
      
      // 关闭支付弹窗
      this.showBuyModal = false;
      
      // 显示支付接口返回的msg信息
      let toastTitle = '支付请求成功';
      if (paymentData.response && paymentData.response.msg) {
        toastTitle = paymentData.response.msg;
      }
      
      uni.showToast({
        title: toastTitle,
        icon: 'success',
        duration: 1500
      });
      
      // 跳转到订单详情页面
      setTimeout(() => {
        uni.navigateTo({
          url: `/pages/order/buydetail?orderId=${this.currentOrderId}`
        });
      }, 1500);
    },
    
    // 处理支付
    handlePayment(paymentData) {
      console.log('支付数据:', paymentData)
      
      // 关闭弹窗
      this.showBuyModal = false
      
      // 根据支付方式处理
      switch(paymentData.paymentType) {
        case 'alipay':
          uni.showToast({
            title: '正在跳转支付宝支付...',
            icon: 'none'
          })
          break
        case 'wechat':
          uni.showToast({
            title: '正在跳转微信支付...',
            icon: 'none'
          })
          break
        case 'balance':
          uni.showToast({
            title: '正在使用余额支付...',
            icon: 'none'
          })
          break
      }
      
      // 模拟支付成功后跳转
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/pay/success'
        })
      }, 1500)
    },

    // 获取账号类型列表
    async fetchAccountTypes() {
      try {
        const response = await goodsApi.getGoodsTemps();
        if (response.code === 1 && response.data && response.data.length > 0) {
          // 获取第一个账号类型模板的temp_list
          this.accountTypes = response.data[0].temp_list || [];
        }
      } catch (error) {
        console.error('获取账号类型失败:', error);
      }
    },
    
    // 加载商品详情
    async fetchGoodsInfo() {
      if (!this.goodsId || this.loading) return;
      this.loading = true;
      try {
        const res = await goodsApi.getGoodsInfo(this.goodsId);
        
        if (res?.data) {
          const goodsInfo = res.data;
          this.currentGoodsInfo = {
            title: goodsInfo.goods_name || goodsInfo.title || '',
            price: goodsInfo.price || '0.00',
            stock: goodsInfo.num || goodsInfo.stock || '0',
            image: (goodsInfo.imgs && goodsInfo.imgs.length > 0) ? String(goodsInfo.imgs[0]).replace(/`/g, '') : this.currentGoodsInfo.image,
            desc: goodsInfo.desc || '',
            content: goodsInfo.content || '',
            cost_price: goodsInfo.cost_price || '0.00',
            class_name: goodsInfo.class_name || '',
            unit: goodsInfo.unit || this.currentGoodsInfo.unit || '个',
            type: goodsInfo.type || 1, // 商品类型：1-话费充值，2-卡密商品，3-权益充值
            specs: goodsInfo.specs || [], // 商品规格列表
            channel_ids: goodsInfo.channel_ids || [], // 支持的渠道ID列表
            carmines: goodsInfo.carmines || {} // 卡密商品的价格库存数据
          };
          
          // 如果有规格，默认选择第一个规格
          if (this.currentGoodsInfo.specs && this.currentGoodsInfo.specs.length > 0) {
            this.selectedSpec = this.currentGoodsInfo.specs[0];
            // 对于非卡密商品，更新价格和库存为第一个规格的价格和库存
            if (this.currentGoodsInfo.type !== 2) {
              this.currentGoodsInfo.price = this.selectedSpec.price || '0.00';
              this.currentGoodsInfo.stock = this.selectedSpec.num || '0';
            }
          }
          
          // 如果商品类型为3，获取账号类型数据
          if (this.currentGoodsInfo.type === 3) {
            this.fetchAccountTypes();
          }
        } else if (res?.code === 0 && res?.msg) {
          uni.showToast({ title: res.msg, icon: 'none' });
        }
      } catch (err) {
        console.error('获取商品详情失败:', err);
        uni.showToast({ title: err?.message || '加载商品详情失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },

    // 选择商品规格
    selectSpec(spec) {
      this.selectedSpec = spec;
      // 对于非卡密商品，更新价格和库存为选中规格的价格和库存
      if (this.currentGoodsInfo.type !== 2) {
        this.currentGoodsInfo.price = spec.price || '0.00';
        this.currentGoodsInfo.stock = spec.num || '0';
      }
      // 重置购买数量为1
      this.quantity = 1;
      // 重置选中的卡密
      this.selectedCarmine = null;
    },

    // 获取当前规格的卡密选项
    getCarmineOptions() {
      if (!this.currentGoodsInfo.carmines || !this.selectedSpec) {
        return [];
      }
      
      const specId = this.selectedSpec.id;
      const carmineData = this.currentGoodsInfo.carmines[specId];
      const options = [];
      
      if (carmineData) {
        // 遍历carmineData对象，end_time为对象键
        Object.keys(carmineData).forEach(endTime => {
          const priceList = carmineData[endTime];
          if (Array.isArray(priceList)) {
            // 遍历价格列表
            priceList.forEach(item => {
              if (item.price && item.allcount > 0) {
                options.push({
                  price: item.price,
                  allcount: item.allcount,
                  end_time: endTime
                });
              }
            });
          }
        });
      }
      
      // 按价格排序
      return options.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
    },

    // 选择卡密
    selectCarmine(carmine) {
      this.selectedCarmine = carmine;
      // 更新商品价格为选中卡密的价格
      this.currentGoodsInfo.price = carmine.price;
    },

    // 获取过期时间文本
    getExpireText(endTime) {
      if (endTime === '0' || endTime === 0) {
        return '永久有效';
      }
      const hours = endTime * 24;
      return `${hours}小时内有效售后`;
    },

    // 构造carmines参数（订单类型为2时使用）
    buildCarminesParams() {
      const carminesArray = [];
      
      // 如果用户选择了特定的卡密，只返回选中的卡密信息
      if (this.selectedCarmine) {
        carminesArray.push({
          price: this.selectedCarmine.price,
          num: this.quantity, // 使用用户选择的购买数量
          end_time: this.selectedCarmine.end_time
        });
        return carminesArray;
      }
      
      // 如果没有选择特定卡密，返回空数组（需要用户先选择）
      return carminesArray;
    },

    // 获取当前价格（卡密商品从子组件获取，其他商品从规格或商品信息获取）
    getCurrentPrice() {
      if (this.currentGoodsInfo.type === 2) {
        // 卡密商品：调用子组件的getCurrentPrice方法
        const cardKeyGoods = this.$refs.cardKeyGoods;
        if (cardKeyGoods && typeof cardKeyGoods.getCurrentPrice === 'function') {
          return cardKeyGoods.getCurrentPrice();
        }
        
        // 子组件未加载时的默认逻辑
        // 优先使用CardKeyGoods组件计算的总价格
        if (this.cardKeyOrderParams && this.cardKeyOrderParams.totalPrice !== undefined) {
          return this.cardKeyOrderParams.totalPrice.toFixed(2);
        }
        
        // 兜底逻辑：如果选中了具体卡密，显示该卡密的价格
        if (this.selectedCarmine) {
          return this.selectedCarmine.price || '0.00';
        }
        
        // 如果只选择了规格但未选择卡密，显示该规格下最低价格的卡密价格
        if (this.selectedSpec && this.currentGoodsInfo.carmines) {
          const specId = this.selectedSpec.id;
          const carmineData = this.currentGoodsInfo.carmines[specId];
          if (carmineData) {
            let minPrice = null;
            Object.keys(carmineData).forEach(endTime => {
              const priceList = carmineData[endTime];
              if (Array.isArray(priceList) && priceList.length > 0) {
                priceList.forEach(item => {
                  if (item.price && item.allcount > 0) {
                    const price = parseFloat(item.price);
                    if (minPrice === null || price < minPrice) {
                      minPrice = price;
                    }
                  }
                });
              }
            });
            return minPrice !== null ? minPrice.toFixed(2) : (this.selectedSpec.bus_price || this.selectedSpec.price || '0.00');
          }
        }
        // 如果carmines为空，则使用specs中的价格
        return this.selectedSpec ? (this.selectedSpec.bus_price || this.selectedSpec.price || '0.00') : (this.currentGoodsInfo.price || '0.00');
      }
      // 对于非卡密商品，优先使用选中规格的价格
      return this.selectedSpec ? (this.selectedSpec.bus_price || this.selectedSpec.price || '0.00') : (this.currentGoodsInfo.price || '0.00');
    },

    // 获取当前库存（卡密商品从子组件获取，其他商品从规格或商品信息获取）
    getCurrentStock() {
      if (this.currentGoodsInfo.type === 2) {
        // 卡密商品：调用子组件的getCurrentStock方法
        const cardKeyGoods = this.$refs.cardKeyGoods;
        if (cardKeyGoods && typeof cardKeyGoods.getCurrentStock === 'function') {
          return cardKeyGoods.getCurrentStock();
        }
        
        // 如果子组件还未加载，使用默认逻辑
        if (this.selectedCarmine) {
          return this.selectedCarmine.allcount || '0';
        }
        
        // 如果只选择了规格但未选择卡密，显示该规格下所有卡密的总库存
        if (this.selectedSpec && this.currentGoodsInfo.carmines) {
          const specId = this.selectedSpec.id;
          const carmineData = this.currentGoodsInfo.carmines[specId];
          if (carmineData) {
            let totalStock = 0;
            Object.keys(carmineData).forEach(endTime => {
              const priceList = carmineData[endTime];
              if (Array.isArray(priceList)) {
                priceList.forEach(item => {
                  if (item.allcount) {
                    totalStock += parseInt(item.allcount) || 0;
                  }
                });
              }
            });
            return totalStock > 0 ? totalStock : '无';
          }
        }
        return this.selectedSpec ? (this.selectedSpec.num || '0') : (parseInt(this.currentGoodsInfo.stock) || 0);
      }
      
      // 其他商品类型
      if (this.selectedSpec) {
        return this.selectedSpec.num || '0';
      }
      return parseInt(this.currentGoodsInfo.stock) || 0;
    },

    // 处理组件传递的数据
    handleComponentData(data) {
      this.componentAccountData = data;
    },
    
    // 处理规格变化
    handleSpecChange(spec) {
      this.selectedSpec = spec;
      // 触发价格和库存的重新渲染
      this.priceStockUpdateKey++;
    },
    
    // 处理账号变化事件
      handleAccountChange(accountData) {
        console.log('goodsdetail接收到账号数据:', accountData);
        this.componentAccountData = accountData;
      },
    
    // 处理账号类型变化
    handleAccountTypeChange(accountType) {
      this.selectedAccountType = accountType;
    },
    
    // 处理价格库存更新事件
    handlePriceStockUpdate() {
      // 通过改变key值强制重新渲染价格和库存
      this.priceStockUpdateKey++;
    },
    
    // 将后端 content 中可能包含的反引号清理，避免渲染异常
    safeHtml(html) {
      if (!html) return '';
      return String(html).replace(/`/g, '');
    },
    
    // 获取账号数量
      getAccountCount() {
        // 卡密商品不需要账号
        if (this.currentGoodsInfo.type === 2) {
          console.log('卡密商品，账号数量返回1');
          return 1;
        }
        
        // 从组件获取账号数据
        if (this.componentAccountData && this.componentAccountData.accountCount !== undefined) {
          console.log('从组件获取账号数量:', this.componentAccountData.accountCount);
          console.log('组件账号数据:', this.componentAccountData);
          return this.componentAccountData.accountCount;
        }
        
        // 兜底逻辑：使用本地数据
        let count;
        if (this.accountType === 'multiple') {
          count = this.accountList.length;
        } else {
          count = this.accountNumber ? 1 : 0;
        }
        console.log('使用兜底逻辑，账号数量:', count);
        console.log('accountType:', this.accountType, 'accountList:', this.accountList, 'accountNumber:', this.accountNumber);
        return count;
      },

      // 关闭登录引导
      closeLoginGuide() {
        this.showLoginGuide = false;
      },

      // 跳转到登录页面
      goToLogin() {
        this.showLoginGuide = false;
        
        // 检查是否为小程序环境
        // #ifdef MP-WEIXIN
        // 小程序环境，显示授权提示并跳转到微信登录页面
        uni.showModal({
          title: '微信授权登录',
          content: '需要获取您的微信信息进行登录，是否继续？',
          confirmText: '确定',
          cancelText: '取消',
          success: (res) => {
            if (res.confirm) {
              // 用户确认授权，跳转到微信登录页面
              uni.navigateTo({
                url: '/pages/login/wxlogin'
              });
            }
          }
        });
        // #endif
        
        // #ifndef MP-WEIXIN
        // H5或APP环境，跳转到普通登录页面
        uni.navigateTo({
          url: '/pages/login/login'
        });
        // #endif
      },

      // 跳转到注册页面
      goToRegister() {
        this.showLoginGuide = false;
        uni.navigateTo({
          url: '/pages/login/login'
        });
      }
  }
}
</script>

<style scoped>
/* 状态栏样式 */
.status-bar {
  width: 100%;
  background: linear-gradient(180deg, #FF7B80 0%, rgba(244,234,234,0) 100%);
}

.goods-detail-page {
  min-height: 100vh;
  background-color: #F2F2F2;
  padding-bottom: 80px;
}

/* 头部导航栏 */
.header-nav {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 44px;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 4vw;
  z-index: 1000;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.header-back {
  width: 8vw;
  height: 8vw;
  max-width: 32px;
  max-height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.header-back-icon {
  width: 5vw;
  height: 5vw;
  max-width: 20px;
  max-height: 20px;
}

.header-title-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-title {
  font-size: 4vw;
  max-font-size: 16px;
  font-weight: 500;
  color: #333333;
  text-align: center;
}

.header-placeholder {
  width: 8vw;
  max-width: 32px;
  flex-shrink: 0;
}

/* 状态栏占位 */
.status-bar {
  height: calc(var(--status-bar-height, 44px) + 44px);
  background-color: #ffffff;
}

/* 导航栏 */
.nav-bar {
  height: 44px;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  padding: 0 16px;
  gap: 12px;
}

.nav-back {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.nav-search-container {
  flex: 1;
  height: 32px;
}

.nav-search-box {
  height: 100%;
  background-color: #f5f5f5;
  border-radius: 16px;
  display: flex;
  align-items: center;
  padding: 0 12px;
  gap: 8px;
}

.nav-more {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.back-icon, .more-icon {
  width: 20px;
  height: 20px;
}

.search-icon {
  width: 16px;
  height: 16px;
  opacity: 0.6;
}

.search-placeholder {
  font-size: 14px;
  color: #999999;
  flex: 1;
}

/* 商品主图和信息左右布局 */
.goods-main-section {
  display: flex;
  padding: 16px;
  background-color: #ffffff;
  gap: 16px;
  border-radius: 12px;
  margin: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 左侧商品图片 */
.goods-image-section {
  width: 5.5rem;
  height: 5.5rem;
  flex-shrink: 0;
  border-radius: 8px;
  overflow: hidden;
}

.goods-image {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  background-color: #dedcdc;
}

/* 右侧商品信息 */
.goods-info-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-title-section {
  margin-bottom: 12px;
}

.goods-title {
  font-size: 18px;
  font-weight: 500;
  color: #333333;
  line-height: 1.4;
}

.price-section {
  display: flex;
  align-items: center;
  
}

.price-container {
  display: flex;
  align-items: baseline;
}

.price-symbol {
  font-size: 16px;
  font-weight: 500;
  color: #ff4757;
}

.price-number {
  font-size: 24px;
  font-weight: 600;
  color: #ff4757;
}

.stock-info {
  font-size: 14px;
  color: #999999;
  margin-left: 0.5rem;
}

/* 商品类型和时长选择 */
.product-type-section,
.product-duration-section {
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
}

.option-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 0.8rem;
}

.option-btn {
  padding: 0.4rem 0.8rem;
  border: 2px solid #e0e0e0;
  border-radius: 24px;
  background-color: #ffffff;
  transition: all 0.3s ease;
}

.option-btn.active {
  border-color: #ff4757;
  background-color: #fff5f5;
}

.option-text {
  font-size: 14px;
  color: #666666;
}

.option-btn.active .option-text {
  color: #ff4757;
  font-weight: 500;
}

/* 卡密售价选择 */
.carmine-price-section {
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.carmine-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 16px;
}

.carmine-option {
  padding: 16px;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  background-color: #ffffff;
  transition: all 0.3s ease;
  cursor: pointer;
}

.carmine-option.active {
  border-color: #ff4757;
  background-color: #fff5f5;
}

.carmine-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.carmine-price {
  font-size: 18px;
  font-weight: 600;
  color: #ff4757;
}

.carmine-stock {
  font-size: 12px;
  color: #666666;
  background-color: #f8f9fa;
  padding: 4px 8px;
  border-radius: 12px;
}

.carmine-expire {
  font-size: 12px;
  color: #666666;
  background-color: #fff3cd;
  padding: 4px 8px;
  border-radius: 12px;
  border: 1px solid #ffeaa7;
}

.no-carmine-data {
  padding: 40px 20px;
  text-align: center;
}

.no-data-icon {
  width: 80px;
  height: 80px;
  margin: 0 auto 20px;
  display: block;
}

.no-data-text {
  font-size: 14px;
  color: #999999;
  line-height: 1.5;
}

.carmine-option.active .carmine-price {
  color: #ff4757;
}

.carmine-option.active .carmine-stock {
  background-color: #fff5f5;
  color: #ff4757;
}

.carmine-option.active .carmine-expire {
  background-color: #fff5f5;
  color: #ff4757;
  border-color: #ff4757;
}

/* 充值账号填写 */
.account-section {
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 充值账号三列布局容器 */
.account-header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  padding: 0 8px;
}

.account-header-container .section-title {
  flex: 1;
  font-size: 16px;
  font-weight: 600;
  color: #333333;
  margin: 0;
}

.account-type-options {
  display: flex;
  gap: 24px;
  margin-bottom: 0.5rem;
  margin-top: 0.5rem;
}

.account-type-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 8px;
  transition: background-color 0.3s ease;
}

.account-type-btn:hover {
  background-color: #f8f9fa;
}

.account-header-container .account-type-btn {
  flex: 0 0 auto;
}

.radio-icon {
  width: 12px;
  height: 12px;
  border: 2px solid #e0e0e0;
  border-radius: 50%;
  background-color: #ffffff;
  position: relative;
  transition: all 0.3s ease;
}

.radio-icon.active {
  border-color: #ff4757;
  background-color: #ff4757;
}

.radio-icon.active::after {
  content: '✓';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #ffffff;
  font-size: 12px;
  font-weight: bold;
}

.account-type-text {
  font-size: 14px;
  color: #333333;
}

/* 输入框和添加按钮两列布局容器 */
.account-input-container {
  margin-top: 16px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.account-input {
  width: 100%;
  height: 36px;
  padding: 0 56px 0 16px;
  border: 1px solid #e0e0e0;
  border-radius: 24px;
  background-color: #f8f9fa;
  font-size: 14px;
  color: #333333;
  outline: none;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.account-input:focus {
  border-color: #ff4757;
  background-color: #ffffff;
}

.account-input::placeholder {
  color: #999999;
}

.add-account-btn {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: #999999;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.add-account-btn:hover {
  background-color: #777777;
  transform: scale(1.05);
}

.add-icon {
  font-size: 24px;
  color: #ffffff;
  font-weight: bold;
}

.add-icon-img {
  width: 24px;
  height: 24px;
}

.floating-icon {
  position: absolute;
  right: 1rem;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 10;
}

.floating-icon:hover {
  transform: translateY(-50%) scale(1.1);
}

/* 多账号列表 */
.account-list {
  margin-top: 16px;
  max-height: 200px;
  overflow-y: auto;
}

.account-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 16px;
  margin-bottom: 8px;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 20px;
  transition: all 0.3s ease;
  height: 24px;
}

.account-item:last-child {
  margin-bottom: 0;
}

.account-item:hover {
  background-color: #e9ecef;
}

.account-text {
  flex: 1;
  font-size: 14px;
  color: #333333;
  word-break: break-all;
}

.remove-account-btn {
  width: 24px;
  height: 24px;
  background-color: #ff4757;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  margin-left: 8px;
  transition: all 0.3s ease;
}

.remove-account-btn:hover {
  background-color: #ff3742;
  transform: scale(1.1);
}

.remove-icon {
  font-size: 16px;
  color: #ffffff;
  font-weight: bold;
  line-height: 1;
}

.remove-icon-img {
  width: 24px;
  height: 24px;
}

/* 购买数量 */
.quantity-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.quantity-label {
  font-size: 14px;
  color: #333333;
}

.quantity-control {
  display: flex;
  align-items: center;
  border: 1px solid #e0e0e0;
  border-radius: 24px;
  background-color: #ffffff;
  overflow: hidden;
}

.quantity-btn {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ffffff;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.quantity-btn:hover {
  background-color: #f8f9fa;
}

.quantity-btn-text {
  font-size: 18px;
  color: #666666;
  font-weight: 500;
}

.add-icon {
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.quantity-value {
  font-size: 16px;
  color: #333333;
  margin: 0 16px;
  min-width: 24px;
  text-align: center;
  font-weight: 500;
}

/* 底部操作栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background-color: #ffffff;
  border-top: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
  padding: 0 16px;
  z-index: 100;
}

.bottom-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.bottom-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.home-icon, .service-icon {
  width: 24px;
  height: 24px;
}

.bottom-btn-text {
  font-size: 10px;
  color: #666666;
}

.bottom-right {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
  margin-left: 20px;
}

.buy-btn {
  flex: 1;
  height: 40px;
  background-color: #ff4757;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.buy-btn-text {
  font-size: 14px;
  color: #ffffff;
  font-weight: 500;
}

/* 成交记录 */
.transaction-section {
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.transaction-table {
  margin-top: 16px;
  border-radius: 8px;
}

.table-header {
  display: flex;
  background-color: #f5f5f5;
  padding: 12px 0;
  border-radius: 0.4rem;
}

.table-body {
  background-color: #ffffff;
}

.table-row {
  display: flex;
  padding: 0.25rem 0;
  

}

.table-row:last-child {
  border-bottom: none;
}

.even-row {
  background-color: #f9f9f9;
  border-radius: 0.5rem;
}

.header-cell, .body-cell {
  flex: 1;
  text-align: center;
  font-size: 14px;
}

.header-cell {
  color: #666666;
  font-weight: 500;
}

.body-cell {
  color: #333333;
}

.time-cell {
  flex: 1.2;
}

.price-cell {
  flex: 0.8;
}

.duration-cell {
  flex: 1;
}

/* 销售渠道 */
.channel-section {
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.platform-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 16px;
  margin-bottom: 24px;
  justify-content: flex-start;
}

.platform-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.platform-icon {
  width: 1rem;
  height: 1rem;
  flex-shrink: 0;
}

.platform-text {
  font-size: 0.75rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 500;
}

.platform-item.supported .platform-text {
  color: #111111;
}

.platform-item.unsupported .platform-text {
  color: #999999;
}

/* 保障服务板块 */
.guarantee-service-section {
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.guarantee-section {
  display: flex;
  justify-content: space-around;
  padding: 16px;
  border-radius: 8px;
  margin-top: 16px;
}

.guarantee-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.guarantee-icon {
  width: 32px;
  height: 32px;
}

.guarantee-text {
  font-size: 12px;
  color: #666666;
  text-align: center;
}

/* 商品详情板块 */
.product-detail-section {
  padding: 20px 16px;
}

.detail-content {
  margin-top: 16px;
  min-height: 200px;
  border: 2px dashed #e0e0e0;
  border-radius: 8px;
  background-color: #fafafa;
  padding: 8px;
  display: block;
  overflow: hidden;
  word-break: break-word;
}

/* 兜底：针对图片可能带固定尺寸的属性 或 style */
.detail-content :deep(img[width]),
.detail-content :deep(img[height]) {
  width: auto !important;
  height: auto !important;
}

/* 兜底：表格内容滚动且不超出容器 */
.detail-content :deep(table) {
  display: block;
  max-width: 100%;
  overflow-x: auto;
}

/* 使详情内富文本媒体自适应容器（适配 v-html + scoped） */
.detail-content :deep(img),
.detail-content :deep(video),
.detail-content :deep(iframe) {
  max-width: 100% !important;
  height: auto !important;
  display: block;
}

/* 兼容 ::v-deep 语法（不同构建工具写法） */
:deep(.detail-content img),
:deep(.detail-content video),
:deep(.detail-content iframe) {
  max-width: 100% !important;
  height: auto !important;
  display: block;
}

.detail-placeholder {
  text-align: center;
}

.detail-placeholder-text {
  font-size: 14px;
  color: #999999;
  line-height: 1.5;
}
</style>